import React from 'react';
import { useState, useEffect, useContext } from 'react';
import DataContext from './context/DataContext';
import api from './api/api';
import { ToastContainer, Toast } from 'react-bootstrap';
import EditDescription from './EditDescription';
import { useHistory } from 'react-router-dom/cjs/react-router-dom';

const EditUser = () => {

  const history = useHistory();
  const [nickname, setNickname] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [description, setDescription] = useState('');

  const { loginUserId, baseUrl } = useContext(DataContext);
  const [user, setUser] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [toastShow, setToastShow] = useState(false);
  const [toastContent, setToastContent] = useState('');
  const [avatar, setAvatar] = useState(null);

  const handleSubmit = async () => {
    const body = {};
    if (nickname)
      body.nickname = nickname;
    if (email)
      body.email = email;
    if (password)
      body.password = password;
    if (description)
      body.description = description;
    try {
      const response = await api.put(`users/${user.id}`, body);
      if (avatar) {
        const formData = new FormData();
        formData.append('avatar_update', avatar);
        const avatarUploadResponse = await api.put(`users/${user.id}/avatar`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
      }
      setToastContent("修改成功！");
      setTimeout(() => {
        history.push(`/users/${user.id}`);
      }, 1000);
    } catch (error) {
      setToastContent(`修改失败。${error.message}`);
    } finally {
      setToastShow(true);
      setTimeout(() => {
        setToastShow(false);
      }, 3000);
    }
  };

  useEffect(() => {
    const getUser = async () => {
      try {
        const meResponse = await api.get(`/users/${loginUserId}`);
        const returnedUser = meResponse.data;
        returnedUser.avatarUrl = `${baseUrl}/users/${returnedUser.id}/avatar`;
        setUser(returnedUser);
        setIsLoading(false);
        setDescription(returnedUser.description);
      } catch (error) {
        console.log(error);
      }
    };
    getUser();
  }, [loginUserId, baseUrl]);

  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container d-flex flex-column align-items-center">
        <h1 className='mt-2 mb-5'>修改用户信息</h1>
        {!isLoading &&
          <>
            <form className='mb-2' onSubmit={(e) => e.preventDefault()}>
              <div className="mb-3">
                <label for="username" className="form-label">昵称</label>
                <input type="text" className="form-control" id="username" placeholder={user.nickname} onChange={(e) => setNickname(e.target.value)} />
              </div>
              <div className="mb-3">
                <label for="email" className="form-label">邮箱</label>
                <input type="text" className="form-control" id="email" placeholder={user.email} onChange={(e) => setEmail(e.target.value)} />
              </div>
              <div className="mb-3">
                <label for="password" className="form-label">密码</label>
                <input type="password" className="form-control" id="password" onChange={(e) => setPassword(e.target.value)} />
              </div>
              <div className='mb-3'>
                <label for="description" className="form-label">描述</label>
                <EditDescription description={description} setDescription={setDescription} />
              </div>
              <div className="mb-3">
                <label for="avatar" className="form-label">头像</label>
                <input type="file" className="form-control" id="avatar" onChange={(e) => setAvatar(e.target.files[0])} />
              </div>
              <div className="text-center mb-4">
                <button type="submit" className="btn btn-primary" onClick={handleSubmit}>提交</button>
              </div>
            </form>
          </>
        }
      </div>
      <ToastContainer position='middle-center' className='m-2'>
        <Toast show={toastShow} onClose={() => { setToastShow(false); }}>
          <Toast.Header>
            <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
            <strong className="me-auto">雨呓</strong>
          </Toast.Header>
          <Toast.Body>{toastContent}</Toast.Body>
        </Toast>
      </ToastContainer>
    </div>
  );
};

export default EditUser;
